package com.lzt.admin.common.security.core;

import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzt.admin.api.captcha.CaptchaAPI;
import com.lzt.admin.common.redis.config.RedisCore;
import com.lzt.admin.common.security.config.SecurityProperies;
import com.lzt.admin.system.service.SysConfigService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class SecurityVerify implements CaptchaAPI {
    private final SysConfigService configService;
    public void verifyCode(HttpServletRequest request, SecurityProperies securityProperties) throws JsonProcessingException {
        String captcha = "";
        String uuid = "";
        if (configService.selectCaptchaEnabled()) {
            if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
                try {
                    Map<String, String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                    captcha = map.get(securityProperties.getCaptcha());
                    uuid = map.get(securityProperties.getUuid());
                } catch (Exception ex) {
                    throw new BadCredentialsException(CAPTCHA_EXCEPTION);
                }

            } else {
                captcha = request.getParameter(securityProperties.getCaptcha());
                uuid = request.getParameter(securityProperties.getUuid());
            }
            RedisCore redisCache = (RedisCore) SpringUtil.getBean(RedisCore.class);
            String verifyKey = CAPTCHA_CODE_KEY + Optional.ofNullable(uuid).orElse("");
            String code = redisCache.getCacheObject(verifyKey);
            Optional.ofNullable(code).orElseThrow(()->new BadCredentialsException(CAPTCHA_EXPIRER));
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha)) {
                throw new BadCredentialsException(CAPTCHA_BAD);
            }
        }
    }
}
